package qjc.j_回溯;

import java.util.ArrayList;
import java.util.List;

public class j4_组合总和 {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        List<Integer> output = new ArrayList<>();
        backtrack(res, output, target, 0, candidates);
        return res;
    }

    private void backtrack(List<List<Integer>> res, List<Integer> output, int target, int start, int[] candidates) {
        if (target == 0) {
            res.add(new ArrayList<>(output));
        }
        if (target < 0) {
            return;
        }
        for (int i = start; i < candidates.length; i++) {
            output.add(candidates[i]);
            backtrack(res, output, target - candidates[i], i, candidates);
            output.remove(output.size() - 1);
        }
    }
}
